package com.vinfai.thread.tradition;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.sun.jmx.remote.internal.ArrayQueue;

/**
 * 线程中断
 * Thread.interrupt()方法不会中断一个正在运行的线程。
 * 
 * 虚假唤醒情况发生，通过变量来中断子程序的运行.
 * 
 * 
 * 这一方法实际上完成的是，在线程受到阻塞时抛出一个中断信号，这样线程就得以退出阻塞的状态。
 * 更确切的说，如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞，
 * 那么，它将接收到一个中断异常（InterruptedException），从而提早地终结被阻塞状态。但线程状态会被重设为false. 

理解： 调用Thread.interrupt() 方法自是【提早地终结被阻塞状态】(不让其一直等待.....)，到可运行状态.... 从而可根据循环变量退出程序。
   @see ThreadInterrupt2.java
 * @author vinfai
 *
 */
public class ThreadInterrupt {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		Queue<String> queue = new ArrayBlockingQueue<String>(10);
		/*MyInterruptThread t = new MyInterruptThread();
		t.start();
		Thread.sleep(1000*10);
		t.shutDownThread();
		System.out.println("t is alive : "+t.isAlive());
		Thread.sleep(3000);
		System.out.println("t is interrupted : "+t.isInterrupted());
		*/
		System.out.println("Main:begin");  
		MyInterruptThread t=new MyInterruptThread();  
        try {  
            t.start();  
            Thread.sleep(1000);  
            System.out.println("Main:shutDownRequest");  
            t.shutDownThread(); 
           // t.interrupt();
            System.out.println("========================================================");
            System.out.println("interrupt.............................");
            System.out.println("========================================================");
            System.out.println("Main:join");  
            //t.join();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
          
        System.out.println(t.isAlive());  
        System.out.println("Main:end");  
        System.out.println("Main:end t:"+t.isInterrupted());  
	}

}
/**
 * 结果：1.可能不中断，运行完成停止。因为调用interrupt();
 * 2.调用interrupt() 方法时 子线程正阻塞 如 sleep. java.lang.InterruptedException: sleep interrupted 
	
	解决推出方法：在调用interrupt();前先设置共享变量参数.
Main:begin
do working now :1
do working now :2
do working now :3
do working now :4
do working now :5
Main:shutDownRequest
Main:join
doShutdown:counter=5
true
Main:end
 */

class MyInterruptThread extends Thread{
	/**
	 * //退出状态，调用interrupt();前设置状态.
	 * 1.当线程没有处于阻塞状态，调用interrupt()方法后线程仍然处于运行状态。在下一个循环时根据needInterrupted状态即可退出死循环。
	 * 2.线程处于阻塞状态，则调用interrupt()方法后直接throw InterruptedException,从阻塞状态中恢复（但如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,）currentThread().isInterrupted()=false. 
	 * 故用currentThread().isInterrupted()判断无效，需要增加变量判断调用interrupt();前设置状态.。见ThreadInterrupt2.java
	 */
	private boolean needInterrupted ; 
	
	BlockingQueue<String> queue  = new ArrayBlockingQueue<String>(10);
	
	private int count = 0;
	public void shutDownThread(){
		needInterrupted = true;
		this.interrupt();
	}
	@Override
	public void run() {
		try {
			System.out.println(Thread.currentThread().getName()+"interrupted state:"+needInterrupted);
			//while(!needInterrupted){ // 变量在没有被中断
			while(!Thread.currentThread().isInterrupted()){
				doWork();
				//Thread.sleep(1000);
				/*Thread t2 = new Thread(new Runnable() {
					@Override
					public void run() {
							System.out.println("helloworld..........");
					}
				});
				t2.start();
				t2.join();*/
				//queue.take();//java5阻塞队列.
			}
		/*} catch (InterruptedException e) {
			System.out.println("线程被中断!");
			//System.out.println("state : "+Thread.interrupted());
			//System.out.println("state2 : "+this.isInterrupted());
			e.printStackTrace();
		*/}finally{  
            //doShutdown();  
        }  
		/*while(true){
			doWork();
			Thread.yield();
		}*/
		System.out.println("Thread.isInterrupted():"+this.isInterrupted());
		System.out.println("Thread.interrupted():"+Thread.interrupted());
		System.out.println(Thread.currentThread().getName()+"interrupted state2:"+needInterrupted);
//		while(!needInterrupted){
//			System.out.println("runing....");
//			try {
//				Thread.sleep(1000);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		}
//		System.out.println("Thread END....");
	}
	private void doWork(){
		count++;
		double d = 0.0d;
		for (int i = 0; i < 900000; i++) {  
            d = d + (Math.PI + Math.E) / d;  
        }  
		System.out.println("do working now :"+count);
	}
	private void doShutdown(){  
        System.out.println("doShutdown:counter="+count);
    }  

}
